gpuParticleSystem.ts 59 KB

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