gpuParticleSystem.ts 61 KB

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