babylon.gpuParticleSystem.ts 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436
  1. module BABYLON {
  2. /**
  3. * This represents a GPU particle system in Babylon
  4. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  5. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  6. */
  7. export class GPUParticleSystem implements IDisposable, IParticleSystem, IAnimatable {
  8. /**
  9. * The id of the Particle system.
  10. */
  11. public id: string;
  12. /**
  13. * The friendly name of the Particle system.
  14. */
  15. public name: string;
  16. /**
  17. * The emitter represents the Mesh or position we are attaching the particle system to.
  18. */
  19. public emitter: Nullable<AbstractMesh | Vector3> = null;
  20. /**
  21. * The rendering group used by the Particle system to chose when to render.
  22. */
  23. public renderingGroupId = 0;
  24. /**
  25. * The layer mask we are rendering the particles through.
  26. */
  27. public layerMask: number = 0x0FFFFFFF;
  28. private _capacity: number;
  29. private _activeCount: number;
  30. private _currentActiveCount: number;
  31. private _accumulatedCount = 0;
  32. private _renderEffect: Effect;
  33. private _updateEffect: Effect;
  34. private _buffer0: Buffer;
  35. private _buffer1: Buffer;
  36. private _spriteBuffer: Buffer;
  37. private _updateVAO: Array<WebGLVertexArrayObject>;
  38. private _renderVAO: Array<WebGLVertexArrayObject>;
  39. private _targetIndex = 0;
  40. private _sourceBuffer: Buffer;
  41. private _targetBuffer: Buffer;
  42. private _scene: Scene;
  43. private _engine: Engine;
  44. private _currentRenderId = -1;
  45. private _started = false;
  46. private _stopped = false;
  47. private _timeDelta = 0;
  48. private _randomTexture: RawTexture;
  49. private _randomTexture2: RawTexture;
  50. private _attributesStrideSize = 21;
  51. private _updateEffectOptions: EffectCreationOptions;
  52. private _randomTextureSize: number;
  53. private _actualFrame = 0;
  54. private readonly _rawTextureWidth = 256;
  55. /**
  56. * List of animations used by the particle system.
  57. */
  58. public animations: Animation[] = [];
  59. /**
  60. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  61. */
  62. public static get IsSupported(): boolean {
  63. if (!Engine.LastCreatedEngine) {
  64. return false;
  65. }
  66. return Engine.LastCreatedEngine.webGLVersion > 1;
  67. }
  68. /**
  69. * An event triggered when the system is disposed.
  70. */
  71. public onDisposeObservable = new Observable<GPUParticleSystem>();
  72. /**
  73. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  74. */
  75. public updateSpeed = 0.01;
  76. /**
  77. * The amount of time the particle system is running (depends of the overall update speed).
  78. */
  79. public targetStopDuration = 0;
  80. /**
  81. * The texture used to render each particle. (this can be a spritesheet)
  82. */
  83. public particleTexture: Nullable<Texture>;
  84. /**
  85. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  86. */
  87. public blendMode = ParticleSystem.BLENDMODE_ONEONE;
  88. /**
  89. * Minimum life time of emitting particles.
  90. */
  91. public minLifeTime = 1;
  92. /**
  93. * Maximum life time of emitting particles.
  94. */
  95. public maxLifeTime = 1;
  96. /**
  97. * Minimum Size of emitting particles.
  98. */
  99. public minSize = 1;
  100. /**
  101. * Maximum Size of emitting particles.
  102. */
  103. public maxSize = 1;
  104. /**
  105. * Minimum scale of emitting particles on X axis.
  106. */
  107. public minScaleX = 1;
  108. /**
  109. * Maximum scale of emitting particles on X axis.
  110. */
  111. public maxScaleX = 1;
  112. /**
  113. * Minimum scale of emitting particles on Y axis.
  114. */
  115. public minScaleY = 1;
  116. /**
  117. * Maximum scale of emitting particles on Y axis.
  118. */
  119. public maxScaleY = 1;
  120. /**
  121. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  122. */
  123. public color1 = new Color4(1.0, 1.0, 1.0, 1.0);
  124. /**
  125. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  126. */
  127. public color2 = new Color4(1.0, 1.0, 1.0, 1.0);
  128. /**
  129. * Color the particle will have at the end of its lifetime.
  130. */
  131. public colorDead = new Color4(0, 0, 0, 0);
  132. /**
  133. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  134. */
  135. public emitRate = 100;
  136. /**
  137. * You can use gravity if you want to give an orientation to your particles.
  138. */
  139. public gravity = Vector3.Zero();
  140. /**
  141. * Minimum power of emitting particles.
  142. */
  143. public minEmitPower = 1;
  144. /**
  145. * Maximum power of emitting particles.
  146. */
  147. public maxEmitPower = 1;
  148. /**
  149. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  150. */
  151. public minAngularSpeed = 0;
  152. /**
  153. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  154. */
  155. public maxAngularSpeed = 0;
  156. /**
  157. * The particle emitter type defines the emitter used by the particle system.
  158. * It can be for example box, sphere, or cone...
  159. */
  160. public particleEmitterType: Nullable<IParticleEmitterType>;
  161. /**
  162. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  163. * This only works when particleEmitterTyps is a BoxParticleEmitter
  164. */
  165. public get direction1(): Vector3 {
  166. if ((<BoxParticleEmitter>this.particleEmitterType).direction1) {
  167. return (<BoxParticleEmitter>this.particleEmitterType).direction1;
  168. }
  169. return Vector3.Zero();
  170. }
  171. public set direction1(value: Vector3) {
  172. if ((<BoxParticleEmitter>this.particleEmitterType).direction1) {
  173. (<BoxParticleEmitter>this.particleEmitterType).direction1 = value;
  174. }
  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 direction2(): Vector3 {
  181. if ((<BoxParticleEmitter>this.particleEmitterType).direction2) {
  182. return (<BoxParticleEmitter>this.particleEmitterType).direction2;
  183. }
  184. return Vector3.Zero();
  185. }
  186. public set direction2(value: Vector3) {
  187. if ((<BoxParticleEmitter>this.particleEmitterType).direction2) {
  188. (<BoxParticleEmitter>this.particleEmitterType).direction2 = value;
  189. }
  190. }
  191. /**
  192. * 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.
  193. * This only works when particleEmitterTyps is a BoxParticleEmitter
  194. */
  195. public get minEmitBox(): Vector3 {
  196. if ((<BoxParticleEmitter>this.particleEmitterType).minEmitBox) {
  197. return (<BoxParticleEmitter>this.particleEmitterType).minEmitBox;
  198. }
  199. return Vector3.Zero();
  200. }
  201. public set minEmitBox(value: Vector3) {
  202. if ((<BoxParticleEmitter>this.particleEmitterType).minEmitBox) {
  203. (<BoxParticleEmitter>this.particleEmitterType).minEmitBox = value;
  204. }
  205. }
  206. /**
  207. * 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.
  208. * This only works when particleEmitterTyps is a BoxParticleEmitter
  209. */
  210. public get maxEmitBox(): Vector3 {
  211. if ((<BoxParticleEmitter>this.particleEmitterType).maxEmitBox) {
  212. return (<BoxParticleEmitter>this.particleEmitterType).maxEmitBox;
  213. }
  214. return Vector3.Zero();
  215. }
  216. public set maxEmitBox(value: Vector3) {
  217. if ((<BoxParticleEmitter>this.particleEmitterType).maxEmitBox) {
  218. (<BoxParticleEmitter>this.particleEmitterType).maxEmitBox = value;
  219. }
  220. }
  221. /**
  222. * Gets the maximum number of particles active at the same time.
  223. * @returns The max number of active particles.
  224. */
  225. public getCapacity(): number {
  226. return this._capacity;
  227. }
  228. /**
  229. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  230. * to override the particles.
  231. */
  232. public forceDepthWrite = false;
  233. /**
  234. * Gets or set the number of active particles
  235. */
  236. public get activeParticleCount(): number {
  237. return this._activeCount;
  238. }
  239. public set activeParticleCount(value: number) {
  240. this._activeCount = Math.min(value, this._capacity);
  241. }
  242. private _preWarmDone = false;
  243. /** 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 */
  244. public preWarmCycles = 0;
  245. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  246. public preWarmStepOffset = 1;
  247. /**
  248. * Gets or sets the minimal initial rotation in radians.
  249. */
  250. public minInitialRotation = 0;
  251. /**
  252. * Gets or sets the maximal initial rotation in radians.
  253. */
  254. public maxInitialRotation = 0;
  255. /**
  256. * 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)
  257. */
  258. public spriteCellChangeSpeed = 1;
  259. /**
  260. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  261. */
  262. public startSpriteCellID = 0;
  263. /**
  264. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  265. */
  266. public endSpriteCellID = 0;
  267. /**
  268. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  269. */
  270. public spriteCellWidth = 0;
  271. /**
  272. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  273. */
  274. public spriteCellHeight = 0;
  275. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  276. public translationPivot = new Vector2(0, 0);
  277. /**
  278. * Gets or sets the billboard mode to use when isBillboardBased = true.
  279. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  280. */
  281. public billboardMode = AbstractMesh.BILLBOARDMODE_ALL;
  282. private _isAnimationSheetEnabled: boolean;
  283. /**
  284. * Gets whether an animation sprite sheet is enabled or not on the particle system
  285. */
  286. public get isAnimationSheetEnabled(): boolean {
  287. return this._isAnimationSheetEnabled;
  288. }
  289. /**
  290. * Is this system ready to be used/rendered
  291. * @return true if the system is ready
  292. */
  293. public isReady(): boolean {
  294. if (!this._updateEffect) {
  295. this._recreateUpdateEffect();
  296. this._recreateRenderEffect();
  297. return false;
  298. }
  299. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  300. return false;
  301. }
  302. return true;
  303. }
  304. /**
  305. * Gets Wether the system has been started.
  306. * @returns True if it has been started, otherwise false.
  307. */
  308. public isStarted(): boolean {
  309. return this._started;
  310. }
  311. /**
  312. * Starts the particle system and begins to emit.
  313. */
  314. public start(): void {
  315. this._started = true;
  316. this._stopped = false;
  317. this._preWarmDone = false;
  318. }
  319. /**
  320. * Stops the particle system.
  321. */
  322. public stop(): void {
  323. this._stopped = true;
  324. }
  325. /**
  326. * Remove all active particles
  327. */
  328. public reset(): void {
  329. this._releaseBuffers();
  330. this._releaseVAOs();
  331. this._currentActiveCount = 0;
  332. this._targetIndex = 0;
  333. }
  334. /**
  335. * Returns the string "GPUParticleSystem"
  336. * @returns a string containing the class name
  337. */
  338. public getClassName(): string {
  339. return "GPUParticleSystem";
  340. }
  341. private _isBillboardBased = true;
  342. /**
  343. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  344. */
  345. public get isBillboardBased(): boolean {
  346. return this._isBillboardBased;
  347. }
  348. public set isBillboardBased(value: boolean) {
  349. if (this._isBillboardBased === value) {
  350. return;
  351. }
  352. this._isBillboardBased = value;
  353. this._releaseBuffers();
  354. }
  355. private _colorGradients: Nullable<Array<ColorGradient>> = null;
  356. private _colorGradientsTexture: RawTexture;
  357. /**
  358. * Gets the current list of color gradients.
  359. * You must use addColorGradient and removeColorGradient to udpate this list
  360. * @returns the list of color gradients
  361. */
  362. public getColorGradients(): Nullable<Array<ColorGradient>> {
  363. return this._colorGradients;
  364. }
  365. /**
  366. * Gets the current list of size gradients.
  367. * You must use addSizeGradient and removeSizeGradient to udpate this list
  368. * @returns the list of size gradients
  369. */
  370. public getSizeGradients(): Nullable<Array<FactorGradient>> {
  371. return this._sizeGradients;
  372. }
  373. /**
  374. * Gets the current list of angular speed gradients.
  375. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  376. * @returns the list of angular speed gradients
  377. */
  378. public getAngularSpeedGradients(): Nullable<Array<FactorGradient>> {
  379. return this._angularSpeedGradients;
  380. }
  381. /**
  382. * Gets the current list of velocity gradients.
  383. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  384. * @returns the list of angular speed gradients
  385. */
  386. public getVelocityGradients(): Nullable<Array<FactorGradient>> {
  387. return this._velocityGradients;
  388. }
  389. private _removeGradient(gradient: number, gradients: Nullable<IValueGradient[]>, texture: RawTexture): GPUParticleSystem {
  390. if (!gradients) {
  391. return this;
  392. }
  393. let index = 0;
  394. for (var valueGradient of gradients) {
  395. if (valueGradient.gradient === gradient) {
  396. gradients.splice(index, 1);
  397. break;
  398. }
  399. index++;
  400. }
  401. if (texture) {
  402. texture.dispose();
  403. }
  404. this._releaseBuffers();
  405. return this;
  406. }
  407. /**
  408. * Adds a new color gradient
  409. * @param gradient defines the gradient to use (between 0 and 1)
  410. * @param color defines the color to affect to the specified gradient
  411. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  412. * @returns the current particle system
  413. */
  414. public addColorGradient(gradient: number, color1: Color4, color2?: Color4): GPUParticleSystem {
  415. if (!this._colorGradients) {
  416. this._colorGradients = [];
  417. }
  418. let colorGradient = new ColorGradient();
  419. colorGradient.gradient = gradient;
  420. colorGradient.color1 = color1;
  421. this._colorGradients.push(colorGradient);
  422. this._colorGradients.sort((a, b) => {
  423. if (a.gradient < b.gradient) {
  424. return -1;
  425. } else if (a.gradient > b.gradient) {
  426. return 1;
  427. }
  428. return 0;
  429. });
  430. if (this._colorGradientsTexture) {
  431. this._colorGradientsTexture.dispose();
  432. (<any>this._colorGradientsTexture) = null;
  433. }
  434. this._releaseBuffers();
  435. return this;
  436. }
  437. /**
  438. * Remove a specific color gradient
  439. * @param gradient defines the gradient to remove
  440. * @returns the current particle system
  441. */
  442. public removeColorGradient(gradient: number): GPUParticleSystem {
  443. this._removeGradient(gradient, this._colorGradients, this._colorGradientsTexture);
  444. (<any>this._colorGradientsTexture) = null;
  445. return this;
  446. }
  447. private _angularSpeedGradients: Nullable<Array<FactorGradient>> = null;
  448. private _angularSpeedGradientsTexture: RawTexture;
  449. private _sizeGradients: Nullable<Array<FactorGradient>> = null;
  450. private _sizeGradientsTexture: RawTexture;
  451. private _velocityGradients: Nullable<Array<FactorGradient>> = null;
  452. private _velocityGradientsTexture: RawTexture;
  453. private _addFactorGradient(factorGradients: FactorGradient[], gradient: number, factor: number) {
  454. let valueGradient = new FactorGradient();
  455. valueGradient.gradient = gradient;
  456. valueGradient.factor1 = factor;
  457. factorGradients.push(valueGradient);
  458. factorGradients.sort((a, b) => {
  459. if (a.gradient < b.gradient) {
  460. return -1;
  461. } else if (a.gradient > b.gradient) {
  462. return 1;
  463. }
  464. return 0;
  465. });
  466. this._releaseBuffers();
  467. }
  468. /**
  469. * Adds a new size gradient
  470. * @param gradient defines the gradient to use (between 0 and 1)
  471. * @param factor defines the size factor to affect to the specified gradient
  472. * @returns the current particle system
  473. */
  474. public addSizeGradient(gradient: number, factor: number): GPUParticleSystem {
  475. if (!this._sizeGradients) {
  476. this._sizeGradients = [];
  477. }
  478. this._addFactorGradient(this._sizeGradients, gradient, factor);
  479. if (this._sizeGradientsTexture) {
  480. this._sizeGradientsTexture.dispose();
  481. (<any>this._sizeGradientsTexture) = null;
  482. }
  483. this._releaseBuffers();
  484. return this;
  485. }
  486. /**
  487. * Remove a specific size gradient
  488. * @param gradient defines the gradient to remove
  489. * @returns the current particle system
  490. */
  491. public removeSizeGradient(gradient: number): GPUParticleSystem {
  492. this._removeGradient(gradient, this._sizeGradients, this._sizeGradientsTexture);
  493. (<any>this._sizeGradientsTexture) = null;
  494. return this;
  495. }
  496. /**
  497. * Adds a new angular speed gradient
  498. * @param gradient defines the gradient to use (between 0 and 1)
  499. * @param factor defines the size factor to affect to the specified gradient
  500. * @returns the current particle system
  501. */
  502. public addAngularSpeedGradient(gradient: number, factor: number): GPUParticleSystem {
  503. if (!this._angularSpeedGradients) {
  504. this._angularSpeedGradients = [];
  505. }
  506. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  507. if (this._angularSpeedGradientsTexture) {
  508. this._angularSpeedGradientsTexture.dispose();
  509. (<any>this._angularSpeedGradientsTexture) = null;
  510. }
  511. this._releaseBuffers();
  512. return this;
  513. }
  514. /**
  515. * Remove a specific angular speed gradient
  516. * @param gradient defines the gradient to remove
  517. * @returns the current particle system
  518. */
  519. public removeAngularSpeedGradient(gradient: number): GPUParticleSystem {
  520. this._removeGradient(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  521. (<any>this._angularSpeedGradientsTexture) = null;
  522. return this;
  523. }
  524. /**
  525. * Adds a new velocity gradient
  526. * @param gradient defines the gradient to use (between 0 and 1)
  527. * @param factor defines the size factor to affect to the specified gradient
  528. * @returns the current particle system
  529. */
  530. public addVelocityGradient(gradient: number, factor: number): GPUParticleSystem {
  531. if (!this._velocityGradients) {
  532. this._velocityGradients = [];
  533. }
  534. this._addFactorGradient(this._velocityGradients, gradient, factor);
  535. if (this._velocityGradientsTexture) {
  536. this._velocityGradientsTexture.dispose();
  537. (<any>this._velocityGradientsTexture) = null;
  538. }
  539. this._releaseBuffers();
  540. return this;
  541. }
  542. /**
  543. * Remove a specific velocity gradient
  544. * @param gradient defines the gradient to remove
  545. * @returns the current particle system
  546. */
  547. public removeVelocityGradient(gradient: number): GPUParticleSystem {
  548. this._removeGradient(gradient, this._velocityGradients, this._velocityGradientsTexture);
  549. (<any>this._velocityGradientsTexture) = null;
  550. return this;
  551. }
  552. /**
  553. * Instantiates a GPU particle system.
  554. * 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.
  555. * @param name The name of the particle system
  556. * @param options The options used to create the system
  557. * @param scene The scene the particle system belongs to
  558. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  559. */
  560. constructor(name: string, options: Partial<{
  561. capacity: number,
  562. randomTextureSize: number
  563. }>, scene: Scene, isAnimationSheetEnabled: boolean = false) {
  564. this.id = name;
  565. this.name = name;
  566. this._scene = scene || Engine.LastCreatedScene;
  567. this._engine = this._scene.getEngine();
  568. if (!options.randomTextureSize) {
  569. delete options.randomTextureSize;
  570. }
  571. let fullOptions = {
  572. capacity: 50000,
  573. randomTextureSize: this._engine.getCaps().maxTextureSize,
  574. ...options
  575. };
  576. var optionsAsNumber = <number>options;
  577. if (isFinite(optionsAsNumber)) {
  578. fullOptions.capacity = optionsAsNumber;
  579. }
  580. this._capacity = fullOptions.capacity;
  581. this._activeCount = fullOptions.capacity;
  582. this._currentActiveCount = 0;
  583. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  584. this._scene.particleSystems.push(this);
  585. this._updateEffectOptions = {
  586. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex"],
  587. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange","gravity", "emitPower",
  588. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  589. "angleRange", "radiusRange", "cellInfos"],
  590. uniformBuffersNames: [],
  591. samplers:["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler"],
  592. defines: "",
  593. fallbacks: null,
  594. onCompiled: null,
  595. onError: null,
  596. indexParameters: null,
  597. maxSimultaneousLights: 0,
  598. transformFeedbackVaryings: []
  599. };
  600. this.particleEmitterType = new BoxParticleEmitter();
  601. // Random data
  602. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  603. var d = [];
  604. for (var i = 0; i < maxTextureSize; ++i) {
  605. d.push(Math.random());
  606. d.push(Math.random());
  607. d.push(Math.random());
  608. d.push(Math.random());
  609. }
  610. this._randomTexture = new RawTexture(new Float32Array(d), maxTextureSize, 1, Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, Texture.NEAREST_SAMPLINGMODE, Engine.TEXTURETYPE_FLOAT);
  611. this._randomTexture.wrapU = Texture.WRAP_ADDRESSMODE;
  612. this._randomTexture.wrapV = Texture.WRAP_ADDRESSMODE;
  613. d = [];
  614. for (var i = 0; i < maxTextureSize; ++i) {
  615. d.push(Math.random());
  616. d.push(Math.random());
  617. d.push(Math.random());
  618. d.push(Math.random());
  619. }
  620. this._randomTexture2 = new RawTexture(new Float32Array(d), maxTextureSize, 1, Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, Texture.NEAREST_SAMPLINGMODE, Engine.TEXTURETYPE_FLOAT);
  621. this._randomTexture2.wrapU = Texture.WRAP_ADDRESSMODE;
  622. this._randomTexture2.wrapV = Texture.WRAP_ADDRESSMODE;
  623. this._randomTextureSize = maxTextureSize;
  624. }
  625. private _createUpdateVAO(source: Buffer): WebGLVertexArrayObject {
  626. let updateVertexBuffers: {[key: string]: VertexBuffer} = {};
  627. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  628. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  629. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  630. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  631. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  632. let offset = 12;
  633. if (!this._colorGradientsTexture) {
  634. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  635. offset += 4;
  636. }
  637. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  638. offset += 3
  639. if (!this._isBillboardBased) {
  640. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  641. offset += 3;
  642. }
  643. if (this._angularSpeedGradientsTexture) {
  644. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  645. offset += 1;
  646. } else {
  647. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  648. offset += 2;
  649. }
  650. if (this._isAnimationSheetEnabled) {
  651. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  652. offset += 1;
  653. }
  654. let vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  655. this._engine.bindArrayBuffer(null);
  656. return vao;
  657. }
  658. private _createRenderVAO(source: Buffer, spriteSource: Buffer): WebGLVertexArrayObject {
  659. let renderVertexBuffers: {[key: string]: VertexBuffer} = {};
  660. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  661. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  662. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  663. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  664. let offset = 12;
  665. if (!this._colorGradientsTexture) {
  666. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  667. offset += 4;
  668. }
  669. offset += 3; // Direction
  670. if (!this._isBillboardBased) {
  671. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  672. offset += 3;
  673. }
  674. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  675. if (this._angularSpeedGradientsTexture) {
  676. offset++;
  677. } else {
  678. offset += 2;
  679. }
  680. if (this._isAnimationSheetEnabled) {
  681. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  682. offset += 1;
  683. }
  684. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  685. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  686. let vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  687. this._engine.bindArrayBuffer(null);
  688. return vao;
  689. }
  690. private _initialize(force = false): void {
  691. if (this._buffer0 && !force) {
  692. return;
  693. }
  694. let engine = this._scene.getEngine();
  695. var data = new Array<float>();
  696. if (!this.isBillboardBased) {
  697. this._attributesStrideSize += 3;
  698. }
  699. if (this._colorGradientsTexture) {
  700. this._attributesStrideSize -= 4;
  701. }
  702. if (this._angularSpeedGradientsTexture) {
  703. this._attributesStrideSize -= 1;
  704. }
  705. if (this._isAnimationSheetEnabled) {
  706. this._attributesStrideSize += 1;
  707. }
  708. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  709. // position
  710. data.push(0.0);
  711. data.push(0.0);
  712. data.push(0.0);
  713. // Age and life
  714. data.push(0.0); // create the particle as a dead one to create a new one at start
  715. data.push(0.0);
  716. // Seed
  717. data.push(Math.random());
  718. data.push(Math.random());
  719. data.push(Math.random());
  720. data.push(Math.random());
  721. // Size
  722. data.push(0.0);
  723. data.push(0.0);
  724. data.push(0.0);
  725. if (!this._colorGradientsTexture) {
  726. // color
  727. data.push(0.0);
  728. data.push(0.0);
  729. data.push(0.0);
  730. data.push(0.0);
  731. }
  732. // direction
  733. data.push(0.0);
  734. data.push(0.0);
  735. data.push(0.0);
  736. if (!this.isBillboardBased) {
  737. // initialDirection
  738. data.push(0.0);
  739. data.push(0.0);
  740. data.push(0.0);
  741. }
  742. // angle
  743. data.push(0.0);
  744. if (!this._angularSpeedGradientsTexture) {
  745. data.push(0.0);
  746. }
  747. if (this._isAnimationSheetEnabled) {
  748. data.push(0.0);
  749. }
  750. }
  751. // Sprite data
  752. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  753. -0.5, 0.5, 0, 1,
  754. -0.5, -0.5, 0, 0,
  755. 0.5, -0.5, 1, 0]);
  756. // Buffers
  757. this._buffer0 = new Buffer(engine, data, false, this._attributesStrideSize);
  758. this._buffer1 = new Buffer(engine, data, false, this._attributesStrideSize);
  759. this._spriteBuffer = new Buffer(engine, spriteData, false, 4);
  760. // Update VAO
  761. this._updateVAO = [];
  762. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  763. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  764. // Render VAO
  765. this._renderVAO = [];
  766. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  767. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  768. // Links
  769. this._sourceBuffer = this._buffer0;
  770. this._targetBuffer = this._buffer1;
  771. }
  772. /** @hidden */
  773. public _recreateUpdateEffect() {
  774. let defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  775. if (this._isBillboardBased) {
  776. defines += "\n#define BILLBOARD";
  777. }
  778. if (this._colorGradientsTexture) {
  779. defines += "\n#define COLORGRADIENTS";
  780. }
  781. if (this._sizeGradientsTexture) {
  782. defines += "\n#define SIZEGRADIENTS";
  783. }
  784. if (this._angularSpeedGradientsTexture) {
  785. defines += "\n#define ANGULARSPEEDGRADIENTS";
  786. }
  787. if (this._velocityGradientsTexture) {
  788. defines += "\n#define VELOCITYGRADIENTS";
  789. }
  790. if (this.isAnimationSheetEnabled) {
  791. defines += "\n#define ANIMATESHEET";
  792. }
  793. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  794. return;
  795. }
  796. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  797. if (!this._colorGradientsTexture) {
  798. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  799. }
  800. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  801. if (!this._isBillboardBased) {
  802. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  803. }
  804. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  805. if (this.isAnimationSheetEnabled) {
  806. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  807. }
  808. this._updateEffectOptions.defines = defines;
  809. this._updateEffect = new Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  810. }
  811. /** @hidden */
  812. public _recreateRenderEffect() {
  813. let defines = "";
  814. if (this._scene.clipPlane) {
  815. defines = "\n#define CLIPPLANE";
  816. }
  817. if (this._isBillboardBased) {
  818. defines += "\n#define BILLBOARD";
  819. switch (this.billboardMode) {
  820. case AbstractMesh.BILLBOARDMODE_Y:
  821. defines += "\n#define BILLBOARDY";
  822. break;
  823. case AbstractMesh.BILLBOARDMODE_ALL:
  824. default:
  825. break;
  826. }
  827. }
  828. if (this._colorGradientsTexture) {
  829. defines += "\n#define COLORGRADIENTS";
  830. }
  831. if (this.isAnimationSheetEnabled) {
  832. defines += "\n#define ANIMATESHEET";
  833. }
  834. if (this._renderEffect && this._renderEffect.defines === defines) {
  835. return;
  836. }
  837. this._renderEffect = new Effect("gpuRenderParticles",
  838. ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"],
  839. ["view", "projection", "colorDead", "invView", "vClipPlane", "sheetInfos", "translationPivot", "eyePosition"],
  840. ["textureSampler", "colorGradientSampler"], this._scene.getEngine(), defines);
  841. }
  842. /**
  843. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  844. * @param preWarm defines if we are in the pre-warmimg phase
  845. */
  846. public animate(preWarm = false): void {
  847. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  848. this._actualFrame += this._timeDelta;
  849. if (!this._stopped) {
  850. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  851. this.stop();
  852. }
  853. }
  854. }
  855. private _createFactorGradientTexture(factorGradients: Nullable<IValueGradient[]>, textureName: string) {
  856. let texture:RawTexture = (<any>this)[textureName];
  857. if (!factorGradients || !factorGradients.length || texture) {
  858. return;
  859. }
  860. let data = new Float32Array(this._rawTextureWidth);
  861. for (var x = 0; x < this._rawTextureWidth; x++) {
  862. var ratio = x / this._rawTextureWidth;
  863. Tools.GetCurrentGradient(ratio, factorGradients, (currentGradient, nextGradient, scale) => {
  864. data[x] = Scalar.Lerp((<FactorGradient>currentGradient).factor1, (<FactorGradient>nextGradient).factor1, scale);
  865. });
  866. }
  867. (<any>this)[textureName] = RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, Texture.NEAREST_SAMPLINGMODE);
  868. }
  869. private _createSizeGradientTexture() {
  870. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  871. }
  872. private _createAngularSpeedGradientTexture() {
  873. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  874. }
  875. private _createVelocityGradientTexture() {
  876. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  877. }
  878. private _createColorGradientTexture() {
  879. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  880. return;
  881. }
  882. let data = new Uint8Array(this._rawTextureWidth * 4);
  883. let tmpColor = Tmp.Color4[0];
  884. for (var x = 0; x < this._rawTextureWidth; x++) {
  885. var ratio = x / this._rawTextureWidth;
  886. Tools.GetCurrentGradient(ratio, this._colorGradients, (currentGradient, nextGradient, scale) => {
  887. Color4.LerpToRef((<ColorGradient>currentGradient).color1, (<ColorGradient>nextGradient).color1, scale, tmpColor);
  888. data[x * 4] = tmpColor.r * 255;
  889. data[x * 4 + 1] = tmpColor.g * 255;
  890. data[x * 4 + 2] = tmpColor.b * 255;
  891. data[x * 4 + 3] = tmpColor.a * 255;
  892. });
  893. }
  894. this._colorGradientsTexture = RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, Texture.NEAREST_SAMPLINGMODE);
  895. }
  896. /**
  897. * Renders the particle system in its current state
  898. * @param preWarm defines if the system should only update the particles but not render them
  899. * @returns the current number of particles
  900. */
  901. public render(preWarm = false): number {
  902. if (!this._started) {
  903. return 0;
  904. }
  905. this._createColorGradientTexture();
  906. this._createSizeGradientTexture();
  907. this._createAngularSpeedGradientTexture();
  908. this._createVelocityGradientTexture();
  909. this._recreateUpdateEffect();
  910. this._recreateRenderEffect();
  911. if (!this.isReady()) {
  912. return 0;
  913. }
  914. if (!preWarm) {
  915. if (!this._preWarmDone && this.preWarmCycles) {
  916. for (var index = 0; index < this.preWarmCycles; index++) {
  917. this.animate(true);
  918. this.render(true);
  919. }
  920. this._preWarmDone = true;
  921. }
  922. if (this._currentRenderId === this._scene.getRenderId()) {
  923. return 0;
  924. }
  925. this._currentRenderId = this._scene.getRenderId();
  926. }
  927. // Get everything ready to render
  928. this._initialize();
  929. this._accumulatedCount += this.emitRate * this._timeDelta;
  930. if (this._accumulatedCount > 1) {
  931. var intPart = this._accumulatedCount | 0;
  932. this._accumulatedCount -= intPart;
  933. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  934. }
  935. if (!this._currentActiveCount) {
  936. return 0;
  937. }
  938. // Enable update effect
  939. this._engine.enableEffect(this._updateEffect);
  940. this._engine.setState(false);
  941. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  942. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  943. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  944. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  945. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  946. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  947. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  948. if (!this._colorGradientsTexture) {
  949. this._updateEffect.setDirectColor4("color1", this.color1);
  950. this._updateEffect.setDirectColor4("color2", this.color2);
  951. }
  952. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  953. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  954. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  955. this._updateEffect.setVector3("gravity", this.gravity);
  956. if (this._sizeGradientsTexture) {
  957. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  958. }
  959. if (this._angularSpeedGradientsTexture) {
  960. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  961. }
  962. if (this._velocityGradientsTexture) {
  963. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  964. }
  965. if (this.particleEmitterType) {
  966. this.particleEmitterType.applyToShader(this._updateEffect);
  967. }
  968. if (this._isAnimationSheetEnabled) {
  969. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  970. }
  971. let emitterWM: Matrix;
  972. if ((<AbstractMesh>this.emitter).position) {
  973. var emitterMesh = (<AbstractMesh>this.emitter);
  974. emitterWM = emitterMesh.getWorldMatrix();
  975. } else {
  976. var emitterPosition = (<Vector3>this.emitter);
  977. emitterWM = Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  978. }
  979. this._updateEffect.setMatrix("emitterWM", emitterWM);
  980. // Bind source VAO
  981. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  982. // Update
  983. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  984. this._engine.setRasterizerState(false);
  985. this._engine.beginTransformFeedback(true);
  986. this._engine.drawArraysType(Material.PointListDrawMode, 0, this._currentActiveCount);
  987. this._engine.endTransformFeedback();
  988. this._engine.setRasterizerState(true);
  989. this._engine.bindTransformFeedbackBuffer(null);
  990. if (!preWarm) {
  991. // Enable render effect
  992. this._engine.enableEffect(this._renderEffect);
  993. let viewMatrix = this._scene.getViewMatrix();
  994. this._renderEffect.setMatrix("view", viewMatrix);
  995. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  996. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  997. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  998. if (this._colorGradientsTexture) {
  999. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  1000. } else {
  1001. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  1002. }
  1003. if (this._isAnimationSheetEnabled && this.particleTexture) {
  1004. let baseSize = this.particleTexture.getBaseSize();
  1005. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  1006. }
  1007. if (this._isBillboardBased) {
  1008. var camera = this._scene.activeCamera!;
  1009. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  1010. }
  1011. if (this._scene.clipPlane) {
  1012. var clipPlane = this._scene.clipPlane;
  1013. var invView = viewMatrix.clone();
  1014. invView.invert();
  1015. this._renderEffect.setMatrix("invView", invView);
  1016. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  1017. }
  1018. // Draw order
  1019. switch(this.blendMode)
  1020. {
  1021. case ParticleSystem.BLENDMODE_ADD:
  1022. this._engine.setAlphaMode(Engine.ALPHA_ADD);
  1023. break;
  1024. case ParticleSystem.BLENDMODE_ONEONE:
  1025. this._engine.setAlphaMode(Engine.ALPHA_ONEONE);
  1026. break;
  1027. case ParticleSystem.BLENDMODE_STANDARD:
  1028. this._engine.setAlphaMode(Engine.ALPHA_COMBINE);
  1029. break;
  1030. }
  1031. if (this.forceDepthWrite) {
  1032. this._engine.setDepthWrite(true);
  1033. }
  1034. // Bind source VAO
  1035. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  1036. // Render
  1037. this._engine.drawArraysType(Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  1038. this._engine.setAlphaMode(Engine.ALPHA_DISABLE);
  1039. }
  1040. // Switch VAOs
  1041. this._targetIndex++;
  1042. if (this._targetIndex === 2) {
  1043. this._targetIndex = 0;
  1044. }
  1045. // Switch buffers
  1046. let tmpBuffer = this._sourceBuffer;
  1047. this._sourceBuffer = this._targetBuffer;
  1048. this._targetBuffer = tmpBuffer;
  1049. return this._currentActiveCount;
  1050. }
  1051. /**
  1052. * Rebuilds the particle system
  1053. */
  1054. public rebuild(): void {
  1055. this._initialize(true);
  1056. }
  1057. private _releaseBuffers() {
  1058. if (this._buffer0) {
  1059. this._buffer0.dispose();
  1060. (<any>this._buffer0) = null;
  1061. }
  1062. if (this._buffer1) {
  1063. this._buffer1.dispose();
  1064. (<any>this._buffer1) = null;
  1065. }
  1066. if (this._spriteBuffer) {
  1067. this._spriteBuffer.dispose();
  1068. (<any>this._spriteBuffer) = null;
  1069. }
  1070. }
  1071. private _releaseVAOs() {
  1072. if (!this._updateVAO) {
  1073. return;
  1074. }
  1075. for (var index = 0; index < this._updateVAO.length; index++) {
  1076. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  1077. }
  1078. this._updateVAO = [];
  1079. for (var index = 0; index < this._renderVAO.length; index++) {
  1080. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  1081. }
  1082. this._renderVAO = [];
  1083. }
  1084. /**
  1085. * Disposes the particle system and free the associated resources
  1086. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  1087. */
  1088. public dispose(disposeTexture = true): void {
  1089. var index = this._scene.particleSystems.indexOf(this);
  1090. if (index > -1) {
  1091. this._scene.particleSystems.splice(index, 1);
  1092. }
  1093. this._releaseBuffers();
  1094. this._releaseVAOs();
  1095. if (this._colorGradientsTexture) {
  1096. this._colorGradientsTexture.dispose();
  1097. (<any>this._colorGradientsTexture) = null;
  1098. }
  1099. if (this._sizeGradientsTexture) {
  1100. this._sizeGradientsTexture.dispose();
  1101. (<any>this._sizeGradientsTexture) = null;
  1102. }
  1103. if (this._angularSpeedGradientsTexture) {
  1104. this._angularSpeedGradientsTexture.dispose();
  1105. (<any>this._angularSpeedGradientsTexture) = null;
  1106. }
  1107. if (this._velocityGradientsTexture) {
  1108. this._velocityGradientsTexture.dispose();
  1109. (<any>this._velocityGradientsTexture) = null;
  1110. }
  1111. if (this._randomTexture) {
  1112. this._randomTexture.dispose();
  1113. (<any>this._randomTexture) = null;
  1114. }
  1115. if (this._randomTexture2) {
  1116. this._randomTexture2.dispose();
  1117. (<any>this._randomTexture2) = null;
  1118. }
  1119. if (disposeTexture && this.particleTexture) {
  1120. this.particleTexture.dispose();
  1121. this.particleTexture = null;
  1122. }
  1123. // Callback
  1124. this.onDisposeObservable.notifyObservers(this);
  1125. this.onDisposeObservable.clear();
  1126. }
  1127. /**
  1128. * Clones the particle system.
  1129. * @param name The name of the cloned object
  1130. * @param newEmitter The new emitter to use
  1131. * @returns the cloned particle system
  1132. */
  1133. public clone(name: string, newEmitter: any): Nullable<GPUParticleSystem> {
  1134. var result = new GPUParticleSystem(name, {capacity: this._capacity, randomTextureSize: this._randomTextureSize}, this._scene);
  1135. Tools.DeepCopy(this, result);
  1136. if (newEmitter === undefined) {
  1137. newEmitter = this.emitter;
  1138. }
  1139. result.emitter = newEmitter;
  1140. if (this.particleTexture) {
  1141. result.particleTexture = new Texture(this.particleTexture.url, this._scene);
  1142. }
  1143. return result;
  1144. }
  1145. /**
  1146. * Serializes the particle system to a JSON object.
  1147. * @returns the JSON object
  1148. */
  1149. public serialize(): any {
  1150. var serializationObject: any = {};
  1151. ParticleSystem._Serialize(serializationObject, this);
  1152. serializationObject.activeParticleCount = this.activeParticleCount;
  1153. return serializationObject;
  1154. }
  1155. /**
  1156. * Parses a JSON object to create a GPU particle system.
  1157. * @param parsedParticleSystem The JSON object to parse
  1158. * @param scene The scene to create the particle system in
  1159. * @param rootUrl The root url to use to load external dependencies like texture
  1160. * @returns the parsed GPU particle system
  1161. */
  1162. public static Parse(parsedParticleSystem: any, scene: Scene, rootUrl: string): GPUParticleSystem {
  1163. var name = parsedParticleSystem.name;
  1164. var particleSystem = new GPUParticleSystem(name, {capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize}, scene);
  1165. if (parsedParticleSystem.activeParticleCount) {
  1166. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  1167. }
  1168. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  1169. return particleSystem;
  1170. }
  1171. }
  1172. }