gpuParticleSystem.ts 61 KB

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